package com.xsz.pda.ui

import android.app.AlertDialog
import android.content.Context
import android.graphics.Color
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.beardedhen.androidbootstrap.BootstrapButton
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.eidlink.idocr.sdk.IDOCRCardType
import com.eidlink.idocr.sdk.bean.EidlinkResult
import com.eidlink.idocr.sdk.listener.OnGetResultListener
import com.xsz.pda.App
import com.xsz.pda.AppExecutors
import com.xsz.pda.Config
import com.xsz.pda.R
import com.xsz.pda.data.bean.Ticket
import com.xsz.pda.data.bean.TicketInfo
import com.xsz.pda.data.bean.TicketWithItem
import com.xsz.pda.data.model.TicketModel
import com.xsz.pda.device.eid.MyNfcManager
import com.xsz.pda.device.eid.NfcListener
import com.xsz.pda.device.eid.ReadCardManager

class SearchActivity : AppCompatActivity() {
    private lateinit var searchEditText: EditText
    private lateinit var listview: RecyclerView
//    private lateinit var searchBtn: BootstrapButton
    private lateinit var backBtn: BootstrapButton
    private var mNfcAdapter: NfcAdapter? = null
    private var isFirstCheck = false

    private val adapter =  object : BaseQuickAdapter<TicketWithItem, QuickViewHolder>(){
        @RequiresApi(Build.VERSION_CODES.M)
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, twi: TicketWithItem?) {
            val item = twi?.ticket
            holder.getView<TextView>(R.id.itemIdNumber).text = item!!.idNumber?:""
            holder.getView<TextView>(R.id.itemName).text = item.name?:""

            var seat = ""
            if (!TextUtils.isEmpty(item.areaName)) {
                seat += item.areaName+ " "
            }
            if (!TextUtils.isEmpty(item.sectorName)) {
                seat += item.sectorName + " "
            }
            if (!TextUtils.isEmpty(item.seat)) {
                seat += item.seat
            }
            val textview = holder.getView<TextView>(R.id.itemSeat)
            val enterOk = Config.getTicketTypeIds().contains(item.ticketTypeId)
            val ti = twi.items[0]
            val timeOk = if (isFirstCheck) ti.chuCanuseTimes>0 else ti.canuseTimes>0
            if (!enterOk ||!timeOk) {
                if (!enterOk) seat += "  通道错误"
                else seat += "  无使用次数"
                textview.setTextColor(Color.RED)
            } else{
                seat += "   请点击验票核销"
                textview.setTextColor(getColor(R.color.bootstrap_brand_success))
            }

            holder.getView<TextView>(R.id.itemSeat).text = seat
            val btn = holder.getView<BootstrapButton>(R.id.btnCheck)
            if (enterOk && timeOk) btn.visibility = View.VISIBLE
            else btn.visibility = View.INVISIBLE
            holder.getView<BootstrapButton>(R.id.btnCheck).setOnClickListener {
                runOnUiThread {  it.visibility = View.INVISIBLE }
                AlertDialog.Builder(this@SearchActivity)
                    .setTitle("提示")
                    .setMessage("确定验票：${item.idNumber}")
                    .setPositiveButton("确定"){d,_->
//                        AppExecutors.diskIO.execute{
//                            val rlt = TicketModel.check(null,null, idNumber = item.idNumber)
//                            if (rlt.third == 0) {
//                                ToastUtils.showShort("验票成功")
//                            }else{
//                                runOnUiThread {  it.visibility = View.VISIBLE }
//                                ToastUtils.showShort(rlt.second)
//                            }
//                        }
                        d.dismiss()
                       AppExecutors.diskIO.execute{ validateTicket(item.name?:"", item.idNumber?:"")}
                    }
                    .setNegativeButton("取消") { d, _ ->
                        runOnUiThread { it.visibility = View.VISIBLE }
                        d.dismiss()
                    }
                    .show()

            }
        }

        override fun onCreateViewHolder(
            context: Context,
            parent: ViewGroup,
            viewType: Int
        ): QuickViewHolder {
            return QuickViewHolder(R.layout.item_search_result, parent)
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        isFirstCheck = Config.isOpenFirstCheck()
        searchEditText = findViewById(R.id.searchEditText)
//        searchBtn = findViewById(R.id.searchBtn)
        listview = findViewById(R.id.resultList)
        backBtn = findViewById(R.id.backBtn)
        backBtn.setOnClickListener { onBackPressed() }
        searchEditText.addTextChangedListener {
            search(searchEditText.text.toString())
        }
//        searchBtn.setOnClickListener {
//            search(searchEditText.text.toString())
//        }
        val ll = LinearLayoutManager(this)
        ll.orientation = LinearLayoutManager.VERTICAL
        listview.layoutManager = ll
        listview.adapter = adapter
    }

    private fun search(txt: String){
        adapter.items = mutableListOf()
        adapter.notifyDataSetChanged()
        if (!TextUtils.isEmpty(txt)&&txt.length >= 6) {
            AppExecutors.diskIO.execute {
                var data = TicketModel.findTicketByIdNumber(txt)
                if (data.isNotEmpty()){
                    if (data.size > 10) {
                        data = data.subList(0,10)
                    }
                    runOnUiThread {
                        adapter.items = data
                        adapter.notifyDataSetChanged()
                    }
                }
                else{
                    ToastUtils.showShort("未查找到数据")
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (App.checkIdCard) {
            mNfcAdapter = MyNfcManager.enableReaderMode(this, object : NfcListener {
                override fun onNfcEvent(tag: Tag?) {
                    if (ReadCardManager.eid == null) {
                        ToastUtils.showShort("eid对象为空，请初始化sdk成功后再使用sdk功能。")
                        return
                    }
                    //二代证读取
                    ReadCardManager.eid.readIDCard(
                        this@SearchActivity,
                        IDOCRCardType.IDCARD, tag,
                        object : OnGetResultListener() {
                            @RequiresApi(Build.VERSION_CODES.M)
                            override fun onSuccess(result: EidlinkResult) {
                                val idNumber = result.getIdentity().getIdnum()
                                val name = result.getIdentity().getName()
                                AppExecutors.diskIO.execute{ validateTicket(name, idNumber)}
                            }
                            @RequiresApi(Build.VERSION_CODES.M)
                            override fun onFailed(code: Int, msg: String, biz_id: String) {
                                Log.i("Main", "读卡失败: $code,$msg,biz_id$biz_id")
                                ToastUtils.showShort(msg)
                            }
                            @RequiresApi(Build.VERSION_CODES.M)
                            override fun onStart() {
                                super.onStart()
                                ToastUtils.showShort("开始读卡,请勿移动")
                            }
                        })
                }
                override fun onNfcError(has: Boolean) {
                    if (has) {
                        ToastUtils.showLong("设备未开启NFC")
                    } else {
                        ToastUtils.showLong("设备不支持NFC")
                    }
                }
            })
        }
    }

    override fun onPause() {
        super.onPause()
        if (App.checkIdCard) {
            MyNfcManager.disableReaderMode(this, mNfcAdapter)
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun validateTicket(name: String, idNumber:String){
        TicketModel.check(null, null,idNumber).apply {
            runOnUiThread {
                val root = layoutInflater.inflate(R.layout.dialog_showinfo, null)
                val showname = root.findViewById<TextView>(R.id.showname)
                val showidnumber = root.findViewById<TextView>(R.id.showidnumber)
                val showseat = root.findViewById<TextView>(R.id.showseat)
                val showToast = root.findViewById<TextView>(R.id.showToast)
                showname.text = "**${name?.last()}"
                showidnumber.text =
                    "${idNumber!!.slice(0..2)}****${idNumber.slice(idNumber.length - 5..idNumber.length - 1)}"
                if (first != null) {
                    showseat.text = first!!.seat
                    showToast.text = "验证成功"
                    showToast.setTextColor(getColor(R.color.bootstrap_brand_success))
                } else {
                    showToast.text = second
                    showToast.setTextColor(Color.RED)
                }
                val dialog = AlertDialog.Builder(this@SearchActivity)
                    .setView(root)
                    .setTitle("验证结果")
                    .setPositiveButton("关闭", null)
                    .show()
                AppExecutors.mainThread.schedule({ dialog.dismiss() }, 3000)
            }
        }
    }
}